/*
 * @Author: yxfan
 * @Date: 2025-03-01 14:22:12
 * @LastEditTime: 2025-03-01 15:54:29
 * @FilePath: \umi-demo\src\components\OverflowTabs\hooks\useVisibleRange.ts
 * @Description:
 */
import { useEffect, useState } from 'react';
import { TabItem, TabOffsetMap } from '../interface';

/**
 * 计算可见标签页的范围
 * @param tabOffsets 标签页偏移量
 * @param containerWidth 容器宽度
 * @param scrollPosition 滚动位置
 * @param tabs 标签页数组
 * @returns [visibleStart, visibleEnd] 可见范围的起始和结束索引
 */
export default function useVisibleRange(
    tabOffsets: TabOffsetMap,
    containerWidth: number,
    scrollPosition: number,
    tabs: TabItem[],
): [number, number] {
    const [visibleRange, setVisibleRange] = useState<[number, number]>([0, 0]);

    useEffect(() => {
        if (!tabs.length) {
            setVisibleRange([0, 0]);
            return;
        }

        let endIndex = tabs.length;
        // 从左到右找到第一个超出可见区域的标签页
        for (let i = 0; i < tabs.length; i++) {
            const offset = tabOffsets.get(tabs[i].key);
            if (
                offset &&
                offset.left + offset.width > scrollPosition + containerWidth
            ) {
                endIndex = i - 1;
                break;
            }
        }

        let startIndex = 0;
        // 从右到左找到第一个进入可见区域的标签页
        for (let i = tabs.length - 1; i >= 0; i--) {
            const offset = tabOffsets.get(tabs[i].key);
            if (offset && offset.left < scrollPosition) {
                startIndex = i + 1;
                break;
            }
        }

        // 确保范围有效
        if (startIndex >= endIndex) {
            setVisibleRange([0, Math.max(0, tabs.length - 1)]);
        } else {
            setVisibleRange([startIndex, endIndex]);
        }
        // debugger
    }, [tabOffsets, containerWidth, scrollPosition, tabs]);

    return visibleRange;
}
